package scrapper;

import java.io.IOException;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.jsoup.Connection;
import org.jsoup.Connection.Method;
import org.jsoup.HttpStatusException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

public class FAScrapper extends AbstractScrapper {

	private String idF;
	private String authorF;
	private String titleF;

	public FAScrapper(String id, String agent) {
		super(id, agent);
	}

	public void breakDownFileName(String filename) {
		Pattern pattern;
		Matcher matcher;
		String title = "";

		pattern = Pattern.compile("^\\d{10}.");
		matcher = pattern.matcher(filename);
		matcher.find();
		setIdF(matcher.group().substring(0, matcher.group().length()-1));

		pattern = Pattern.compile(".([a-z0-9-])+_");
		matcher = pattern.matcher(filename);
		matcher.find();
		setAuthorF(matcher.group().substring(1, matcher.group().length()-1));

		pattern = Pattern.compile("_([a-z0-9-])+");
		matcher = pattern.matcher(filename);
		while(matcher.find())
			title += matcher.group().substring(1, matcher.group().length())+" ";
		setTitleF(title.trim());
	}

	public int performSearch() throws IOException {
		// 1366177101.grisser_houndgrey11.jpg
		// 1366153465.canson_dragons_copy.jpg
		// 1366097264.amwulf_murraylow.png
		// 1274965177.montezuma_hypno
		Connection.Response res = Jsoup.connect("http://www.furaffinity.net/search/")
				.userAgent("Mozilla/5.0 (Windows NT 6.1; WOW64; rv:20.0) Gecko/20100101 Firefox/20.0")
				.cookies(getLoginCookies())
				.data("q", ("@lower "+getAuthorF()+" @filename "+getTitleF()),
						"page", "1",
						"perpage", "60",
						"order-by", "relevancy",
						"order-direction", "dsec",
						"do_search", "Search",
						"range", "all",
						"rating-general", "on",
						"rating-mature", "on",
						"rating-adult", "on",
						"type-art", "on",
						"mode", "extended")
						.method(Method.POST)
						.timeout(0)
						.execute();

		Document page = res.parse();
		String e = page.select("center[class=flow search with-titles-usernames thumb-size-200]").html();
		Pattern pattern;
		Matcher matcher;
		pattern = Pattern.compile("\\d{6,10}@200-"+getIdF());
		matcher = pattern.matcher(e);
		matcher.find();
		
		try {
			setUrl(buildURL(matcher.group().substring(0, matcher.group().length()-(5+getIdF().length()))));
		}
		catch(IllegalStateException ise) {
			return 400;
		}
		
		return 0;
	}

	@Override
	public void login(String username, String password) throws IOException {
		Connection.Response res = Jsoup.connect("https://www.furaffinity.net/login/")
				.userAgent("Mozilla/5.0 (Windows NT 6.1; WOW64; rv:20.0) Gecko/20100101 Firefox/20.0")
				.data("action", "login",
						"retard_protection", "1",
						"name", username,
						"pass", password,
						"login", "Login toÂ FurAffinity")
						.method(Method.POST)
						.timeout(0)
						.execute();
		setLoginCookies(res.cookies());
		for(Entry<String, String> e : getLoginCookies().entrySet())
			System.out.println(e.getValue()+" "+e.getKey());
	}

	@Override
	public String buildURL(String id) { return "http://www.furaffinity.net/view/"+id; }

	@Override
	public boolean buildPage() throws HttpStatusException {
		Pattern pattern;
		Matcher matcher;
		int tmp;

		String rawTitle = getPage().select("title").text();
		if(rawTitle.equals("System Error")) {
			throw new HttpStatusException("System Error", 404, getUrl());
		}
		String rawDate = getPage().select("span[class=popup_date]").get(0).attr("title");
		String rawTags = getPage().select("div[id=keywords]").text();
		String rawDesc = getPage().select("td[width=70%]").text();
		String rawInfo = getPage().select("td").get(10).html();

		pattern = Pattern.compile(" by ");
		matcher = pattern.matcher(rawTitle);
		matcher.find();
		setTitle(rawTitle.substring(0, matcher.start()).replace("&quot;", "\"").trim());

		tmp = matcher.end();
		pattern = Pattern.compile(" -- ");
		matcher = pattern.matcher(rawTitle);
		matcher.find();
		setAuthor(rawTitle.substring(tmp, matcher.start()));

		setDate(rawDate);
		setTags(rawTags.split("   "));
		setDesc(rawDesc.replace(getTitle()+" - by "+getAuthor(), "").trim());

		if(rawInfo.contains("General rating"))
			setSfw(true);
		else
			setSfw(false);
		
		pattern = Pattern.compile("Favorites:</b> \\d*");
		matcher = pattern.matcher(rawInfo);
		matcher.find();
		setFavs(Integer.valueOf(matcher.group().replace("Favorites:</b> ", "")));

		pattern = Pattern.compile("Views:</b> \\d*");
		matcher = pattern.matcher(rawInfo);
		matcher.find();
		setClics(Integer.valueOf(matcher.group().replace("Views:</b> ", "")));
		return true;
	}

	public String getIdF() { return idF; }
	public void setIdF(String idF) { this.idF = idF; }

	public String getAuthorF() { return authorF; }
	public void setAuthorF(String authorF) { this.authorF = authorF; }

	public String getTitleF() { return titleF; }
	public void setTitleF(String titleF) { this.titleF = titleF; }

	public static void main(String[] args) {
		try {
			FAScrapper f1 = new FAScrapper("", "Chrome");
			f1.login("Jimbei", "Dratini147");
			System.out.println("log completed!");
			
			//f1.breakDownFileName("1358267045.hazardbarzard_sc_20hazbaz_20dinorhino_20-_20websized");
			//f1.breakDownFileName("1366305155.kleinebar_comehithersmall");
			f1.breakDownFileName("1366546185.normalize_2013-04-21-jim55_commission");
			f1.performSearch();
			f1.connectWithCookies();
			f1.buildPage();
			
			System.out.println(f1);
			System.out.println("desc - "+f1.getDesc());
			System.out.println("<<TAG>>");
			for(String t : f1.getTags())
				System.out.println(t);
			System.out.println("sfw "+f1.isSfw());
			System.out.println("clics "+f1.getClics());
			System.out.println("favs "+f1.getFavs());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
